<template>
  <div id="root">
  <div class="todo-container">
    <div class="todo-wrap">
     <Header  
     :todos='todos' 
     :addTodosOne='addTodosOne'/>
     <List 
     :todos='todos' 
     :deleteTode='deleteTode'
     />
     <Footer 
     :deleteOne='deleteOne' 
     :todos='todos'
     :checkAll='checkAll'
     v-show="todos.length"
     />
    </div>
  </div>
</div>
</template>

<script>
  import Header from './components/Header'
  import List from './components/List'
  import Footer from './components/Footer'
  export default {
    name:'App',
    data() {
      return {
        todos:JSON.parse(localStorage.getItem('todos')) || [],
      }
    },
    components:{
      Header,
      List,
      Footer
    },
    methods:{
      // 数据在哪里 操作数据的方法在哪里
      // 添加一个todo
      addTodosOne(todoObj){
        // 去除todos中查询是否有同名的todos对象
        const result = this.todos.find(todos => todos.title === todoObj.title)
        if(result){
          // 若有同名的
          alert('不能重复添加!!!')
          return false
        }else{
          // 没有同名的
          this.todos.unshift(todoObj)
          return true
        }
      },
      // 清除已完成任务
      deleteOne(){
        const fltTodos = this.todos.filter(todos => !todos.done)
        this.todos = fltTodos
      },
      // 删除一个todo项
      deleteTode(id){
        // 过滤掉不想要的todo项
        const fltTodos = this.todos.filter(todos => todos.id !== id)
        this.todos = fltTodos
      },
      // 全选全不选
      checkAll(done){
        this.todos.forEach((todo)=>{
          todo.done = done
        })
      }
    },
    // 这里是采用深度监视来储存数据的变化
    watch:{
      todos:{
        deep:true,
        handler(val){
          localStorage.setItem('todos',JSON.stringify(val))
        }
      }
    }
  }
</script>

<style>
  /*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>